// pages/deal/deal.js
const app = getApp()
import { request } from "../../request/index.js";
const bookStatus = {
  up: 0,
  down: 1
}

Page({
  useStore: true,

  /**
   * 页面的初始数据
   */
  data: {
    option1: [
      { text: '完整无污渍', value: 0 },
      { text: '完整少许污渍', value: 1 },
      { text: '轻微破损', value: 2 },
      { text: '严重破损', value: 3 },
    ],
    value1: 0,
    option2: [
      { text: '较无磨损', value: 0 },
      { text: '少量磨损', value: 1 },
      { text: '大面积磨损', value: 2 },
    ],
    value2: 0,
    option3: [
      { text: '较无笔记', value: 0 },
      { text: '少量笔记', value: 1 },
      { text: '大量笔记', value: 2 },
    ],
    value3: 0,
    option4: [
      { text: '最新版本', value: 0 },
      { text: '非最新版本', value: 1 },
    ],
    value4: 0,
    fileList: [],
    allSelect: "circle",
    show: false,
    show1: false,
    ruleShow: false,
    books: [],
    value: '',
    bookItem: {
      titleUrl: '',
      name: '',
      cover: '完整无污渍',
      Degree: '较无磨损',
      notes: '较无笔记',
      edition: '最新版本',
      price: 0,
      bookPhotoUrls: [],
      remark: '',
      bid:'',
    },
    showBooksListDown: [],
    showBooksListUp: [],
    allSelect: "circle",
    count: 0,
    ruleMark: false,
    // 修改删除的...的样式触发
    box: -1,
    bookName: '',
    inMoney:0,
  },
  
  
  // 唤起弹窗
  rulePut() {

    this.setData({
      ruleShow: !this.data.ruleShow
    })
  },

  // 卖书规则
  // rule() {
  //   this.setData({
  //     ruleMark: true
  //   })
  //   if (this.data.ruleMark) {
  //     wx.showModal({
  //       title: '卖书规则',
  //       content: `1.书的收购价格如何确定的？\r\n书的价格根据市场情况动态调整。\r\n
  //       2.什么书不收？\r\n有严重影响阅读及封面完整和美观的破损、污渍、异味等,非卖品和非法出版物。\r\n
  //       3.如何卖书？\r\n用户拍摄书籍质量情况,自行判定书籍情况,自定义价格后上传到平台,并上架书籍。\r\n
  //       4.如何收到卖书的钱？\r\n书籍被订购后平台上门收货验货,完成后即可得到书籍收益。\r\n
  //       5.卖书订单可否取消？\r\n毕业季忙碌,暂时不支持取消订单喔,请大家谨慎上架书籍。\r\n
  //       6.自我审核与平台审核不符如何处理？\r\n平台工作人员会上门收货验货,最终解释权归莓友。`,
  //       confirmText: '知道了',
  //       confirmColor: '#f491bf',
  //       showCancel: false,
  //       success(res) {
  //         if (res.confirm) {
  //           console.log('用户点击确定')
  //           this.setData({
  //             ruleMark: false
  //           })
  //         }
  //       }
  //     })
  //   }
  // },

  // 上传照片
  beforeRead(event) {
    const { file, callback } = event.detail;
    callback(file.type === 'image');
  },
  afterRead(event) {
    console.log(event)
    const file = event.detail.file

    // 还没上传时将选择的图片的上传状态设置为加载
    var that = this
    const fileList = that.data.fileList
    fileList.push({})
    fileList[fileList.length - 1].status = 'uploading'
    that.setData({ fileList })
    this.uploadImg(file.url)
  },
  uploadImg(fileURL) {
    var that = this
    var token = wx.getStorageSync('token')
    // 上传文件
    wx.uploadFile({
      url: 'https://dogborther.top/book/oss/uploadFile', //仅为示例，非真实的接口地址
      header: {
        token: token
      },
      filePath: fileURL,
      name: 'file',
      success(res) {
        console.log(res)
        const fileList = that.data.fileList;
        let data = JSON.parse(res.data)
        console.log(JSON.parse(res.data))
        fileList[fileList.length - 1].url = data.data.url
        fileList[fileList.length - 1].status = 'done'
        that.setData({ fileList });
        console.log("fileList", fileList)
      }, fail(err) {
        console.log(err)
      }
    })
  },

  // 点击预览的x号,将图片删除
  deleteImg(event) {
    // event.detail.index: 删除图片的序号值
    const delIndex = event.detail.index
    const fileList = this.data.fileList

    // 删除（真删除）还没写

    // 页面删除（假删除）
    // 添加或删除 array.splice(index,howmany,item1,.....,itemX)
    fileList.splice(delIndex, 1)
    this.setData({ fileList })
  },

  // 唤起弹窗
  outPut() {
    if (wx.getStorageSync('userPhone') && wx.getStorageSync('add')) {
      this.setData({
        show: !this.data.show
      })
      app.store.setState({
        isrule: false
      })
      this.setData({
        bookName: '',
        inMoney: '',
        ['bookItem.Degree']: this.data.option2[0].text,
        ['bookItem.notes']: this.data.option3[0].text,
        ['bookItem.edition']: this.data.option4[0].text,
        ['bookItem.cover']: this.data.option1[0].text,
        ['bookItem.name']: '',
        value: '',
        ['bookItem.titleUrl']: '',
        ['bookItem.bookPhotoUrls']: [],
        fileList: [],
        ['bookItem.bid']:'',
      })
    }
    else {
      wx.showToast({
        title: '个人信息仍需完善噢',
        icon: 'none',
        duration: 1000
      })
    }
    // this.setData({
    //   show: !this.data.show
    // })
  },

  // 唤起修改弹窗
  updateBook(e){
    var that = this
    console.log(e)
    var id = e.currentTarget.dataset.bid
    request({
      url: '/book/sell/get/'+id,
      method: "GET"
    })
    .then(result=>{
      console.log(result)
      console.log('123')
      that.setData({
        show: !that.data.show
      })
      let list = that.data.fileList
      list.push({status:'done',url:result.data.data.book.bookCoverUrl})
      let arr = JSON.parse(result.data.data.book.bookPhotoUrls);
      arr.forEach(item=>{
        list.push({status:'done',url:item})
      })
      that.setData({
        value2 : that.getIndex(result.data.data.book.injureLevel,that.data.option2),
        value3 : that.getIndex(result.data.data.book.noteLevel,that.data.option3),
        value4 : that.getIndex(result.data.data.book.bookVersion,that.data.option4),
        bookName: result.data.data.book.bookName,
        value: result.data.data.book.bookPrice/100,
        fileList:list,
        inMoney:result.data.data.book.bookPrice/100,
      })
      that.setData({
        ['bookItem.Degree']: result.data.data.book.injureLevel,
        ['bookItem.notes']: result.data.data.book.noteLevel,
        ['bookItem.edition']: result.data.data.book.bookVersion,
        ['bookItem.cover']: this.data.option1[0].text,
        ['bookItem.name']: result.data.data.book.bookName,
        ['bookItem.price']: result.data.data.book.bookPrice,
        ['bookItem.titleUrl']: result.data.data.book.bookCoverUrl,
        ['bookItem.bookPhotoUrls']: JSON.parse(result.data.data.book.bookPhotoUrls),
        ['bookItem.bid']: result.data.data.book.bid,

      })
    })

  },

  
  getIndex(target,arr){
    for(let i=0;i<arr.length;i++){
      if(arr[i].text==target){
        return i;
      }
    }
    return -1;
  },
  //判断价格是否输入数字
  handleInput(e) {
    let value = this.validateNumber(e.detail.value)
    this.setData({
      value
    })
  },

  validateNumber(val) {
    // return val.replace(/\D/g, '')
    return val.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')
  },

  // 下面就是存储输入数据
  // 输入书名
  inName(e) {
    console.log(e)
    this.setData({
      ['bookItem.name']: e.detail.value
    })
    console.log(this.data.bookItem)
  },
  //输入备注
  inRemark(e) {
    console.log(e)
    this.setData({
      ['bookItem.remark']: e.detail.value
    })
    console.log(this.data.bookItem)
  },

  // 封面
  changecover({ detail }) {
    var that = this
    console.log(detail)
    this.setData({
      ['bookItem.cover']: this.data.option1[detail].text,
    })
    console.log(this.data.bookItem)
  },
  // 磨损程度
  changeDegree({ detail }) {
    var that = this
    console.log(detail)
    this.setData({
      ['bookItem.Degree']: this.data.option2[detail].text,
    })
    console.log(this.data.bookItem)
  },
  // 内页笔记
  changenotes({ detail }) {
    var that = this
    console.log(detail)
    this.setData({
      ['bookItem.notes']: this.data.option3[detail].text,
    })
    console.log(this.data.bookItem)
  },
  // 版本
  changeedition({ detail }) {
    var that = this
    console.log(detail)
    this.setData({
      ['bookItem.edition']: this.data.option4[detail].text,
    })
    console.log(this.data.bookItem)
  },

  // 输入价格
  inPrice(e) {
    console.log(e)
    this.setData({
      ['bookItem.price']: e.detail.value,
      inMoney: e.detail.value,

    })
    console.log(this.data.bookItem)
  },

  // 传输数据
  sendMess() {
    const that = this;
    for (let i = 0; i < this.data.fileList.length; i++) {
      if (i === 0) {
        this.setData({
          'bookItem.titleUrl': this.data.fileList[i].url
        })
      }
      else {
        console.log(this.data.fileList[i])
        this.setData({
          [`bookItem.bookPhotoUrls[${i - 1}]`]: this.data.fileList[i].url
        })
      }
    }
    this.setData({
      [`bookItem.bookPhotoUrls`]: JSON.stringify(that.data.bookItem.bookPhotoUrls)
    })
    console.log(this.data.bookItem.titleUrl)
    console.log(this.data.bookItem.bookPhotoUrls)
   
    if (that.data.bookItem.name && that.data.bookItem.price && that.data.bookItem.titleUrl) {
      request({
        url: '/book/sell/addBook', method: "POST",
        data: {
          bookName: that.data.bookItem.name,
          bookLevel: that.data.bookItem.level,
          bookPrice: that.data.bookItem.price * 100,
          bookVersion: that.data.bookItem.edition,
          bookCoverUrl: that.data.bookItem.titleUrl,
          bookPhotoUrls: that.data.bookItem.bookPhotoUrls,
          coverLevel: that.data.bookItem.cover,
          injureLevel: that.data.bookItem.Degree,
          noteLevel: that.data.bookItem.notes,
          bookDesc: that.data.bookItem.remark,
          bid: that.data.bookItem.bid,
        }
      })
        .then(result => {
          console.log(result);
          that.setData({
            show: !that.data.show
          })
          that.onShow()
        })
    }
    else {
      wx.showToast({
        title: '书籍信息尚未齐全',
        icon: 'none',
        duration: 1000
      })
    }
  },

  // 点击下架区选择框
  changeDown: function (e) {
    var that = this
    var index = e.currentTarget.dataset.index
    var select = e.currentTarget.dataset.select
    if (select == "circle") {
      var stype = "success"
    } else {
      var stype = "circle"
    }
    var newList = that.data.showBooksListDown
    newList[index].select = stype
    that.setData({
      showBooksListDown: newList
    })
    console.log(this.data.showBooksListDown)
    // let flag = true
    // for (let i = 0; i < this.data.count; i++) {
    //   if (this.data.showBooksList[i].select === 'circle') {
    //     flag = false;
    //     break
    //   }
    // } 
    // 全选 应该不要了把
    // if (flag) {
    //   this.setData({
    //     allSelect: 'success'
    //   })
    // }
    // else {
    //   this.setData({
    //     allSelect: 'circle'
    //   })
    // }
  },
  // 点击上架区区选择框
  changeUp: function (e) {
    var that = this
    var index = e.currentTarget.dataset.index
    var select = e.currentTarget.dataset.select

    if (select == "circle") {
      var stype = "success"
    } else {
      var stype = "circle"
    }
    var newList = that.data.showBooksListUp
    newList[index].select = stype
    that.setData({
      showBooksListUp: newList
    })
    console.log(this.data.showBooksListUp)
  },
  // 关闭修改的窗口
  // changeBox(){
  //   console.log('69')
  //   this.setData({
  //     box: -1
  //   })
  // },  
  // 唤起已上架...
  changeUpBox(e){
    console.log(e)
    var that = this
    var index = e.currentTarget.dataset.index
    var bid = e.currentTarget.dataset.id
    that.setData({
      box:that.data.box==bid?-1:bid
    })
  },
  // 唤起未上架...
  changeDownBox(e){
    console.log(e)
    var that = this
    var index = e.currentTarget.dataset.index
    var bid = e.currentTarget.dataset.id
    that.setData({
      box:that.data.box==bid?-1:bid
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */

  // 点击上架
  upBook(e) {
    var that = this
    console.log(e)
    var id = e.currentTarget.dataset.bid
    wx.showModal({
      content: '您确定要上架么',
      cancelText: '取消',
      confirmText: '确定',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          request({
            url: '/book/sell/shelves/'+id,
            method: "GET"
          })
          .then(result=>{
            console.log(result)
            console.log('123')
            that.onShow()
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  // 点击删除
  deleteBook(e){
    var that = this
    console.log(e)
    var id = e.currentTarget.dataset.bid
    wx.showModal({
      content: '您确定要删除么',
      cancelText: '取消',
      confirmText: '确定',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          request({
            url: '/book/sell/delete/'+id,
            method: "GET"
          })
          .then(result=>{
            console.log(result)
            console.log('123')
            that.onShow()
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  
  // 点击待上架处的删除 之前的
  deleteDownBook() {
    var that = this
    let readyUp = []
    console.log(this.data.showBooksListDown)
    this.data.showBooksListDown.forEach(r => {
      if (r.select == 'success') {
        readyUp.push(r.bid)
      }
    })
    if (readyUp.length != 0) {
      wx.showModal({
        content: '您确定要删除么',
        cancelText: '取消',
        confirmText: '确定',
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定')
            request({
              url: '/book/sell/delete',
              data: {
                ids: JSON.stringify(readyUp)
              },
              method: "GET"
            })
              .then(result => {
                console.log(result)
                that.onShow()
              })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      console.log(readyUp)
    }
    else {
      wx.showToast({
        title: '还没选择宝贝哦',
        icon: 'none',
        duration: 1000
      })
    }
  },
  // 点击下架
  downBook(e) {
      var that = this
      console.log(e)
      var id = e.currentTarget.dataset.bid
      wx.showModal({
        content: '您确定要下架么',
        cancelText: '取消',
        confirmText: '确定',
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定')
            request({
              url: '/book/sell/withdraw/'+id,
              method: "GET"
            })
            .then(result=>{
              console.log(result)
              console.log('123')
              that.onShow()
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
  },

  // 点击上架中处的删除
  deleteUpBook() {
    var that = this
    let readyUp = []
    console.log(this.data.showBooksListUp)
    this.data.showBooksListUp.forEach(r => {
      if (r.select == 'success') {
        readyUp.push(r.bid)
      }
    })
    if (readyUp.length != 0) {
      wx.showModal({
        content: '您确定要删除么',
        cancelText: '取消',
        confirmText: '确定',
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定')
            request({
              url: '/book/sell/delete',
              data: {
                ids: JSON.stringify(readyUp)
              },
              method: "GET"
            })
              .then(result => {
                console.log(result)
                that.onShow()
              })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      console.log(readyUp)
    }
    else {
      wx.showToast({
        title: '还没选择宝贝哦',
        icon: 'none',
        duration: 1000
      })
    }
  },
  
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // let { isrule } = app.store.getState()
    // if (isrule) {
    //   wx.showModal({
    //     title: '卖书规则',
    //     content: `1.书的收购价格如何确定的？\r\n书的价格根据市场情况动态调整。\r\n
    //     2.什么书不收？\r\n有严重影响阅读及封面完整和美观的破损、污渍、异味等,非卖品和非法出版物。\r\n
    //     3.如何卖书？\r\n用户拍摄书籍质量情况,自行判定书籍情况,自定义价格后上传到平台,并上架书籍。\r\n
    //     4.如何收到卖书的钱？\r\n书籍被订购后平台上门收货验货,完成后即可得到书籍收益。\r\n
    //     5.卖书订单可否取消？\r\n毕业季忙碌,暂时不支持取消订单喔,请大家谨慎上架书籍。\r\n
    //     6.自我审核与平台审核不符如何处理？\r\n平台工作人员会上门收货验货,最终解释权归莓友。`,
    //     cancelText: '不再提醒',
    //     confirmText: '知道了',
    //     confirmColor: '#f491bf',
    //     success(res) {
    //       if (res.confirm) {
    //         console.log('用户点击确定')
    //         app.store.setState({
    //           isrule: false
    //         })
    //       } else if (res.cancel) {
    //         console.log('用户点击不再提醒')
    //         app.store.setState({
    //           isrule: false
    //         })
    //       }
    //     }
    //   })
    // }
    var that = this
    request({ url: '/book/getUpDown' })
      .then(result => {
        console.log(result);
        let listDown = []
        let listUp = []
        let list = result.data.data.list
        list.forEach((r) => {
          r.select = 'circle';
          // 未上架
          if (r.bookStatus === bookStatus.down) {
            listDown.push(r)
          }
          // 已上架
          else if (r.bookStatus === bookStatus.up) {
            listUp.push(r)
          }
        })
        console.log(list)
        that.setData({
          showBooksListDown: listDown,
          showBooksListUp: listUp,
          // count: result.data.data.list.length
        })
        // 未上架
        console.log(this.data.showBooksListDown)
        // 已上架
        console.log(this.data.showBooksListUp)
      })
    // that.setData({
    //   ['bookItem.level']: 5,
    // })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})